package me.wpf.utils;

import org.apache.commons.dbcp2.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * desc : 数据库连接池
 * <p>
 * author : 王朋飞
 */
public class DBHelper {
    private static final Logger LOG = LoggerFactory.getLogger(DBHelper.class);
    //连接池对象
    private static BasicDataSource bds = null;
    static String reg;

    private DBHelper() {
    }

    static {
        try {
            Properties myProp = ConfigPropertiesUtil.getConfigProperties();
            //创建数据库连接池
            bds = new BasicDataSource();
            bds.setDriverClassName(myProp.getProperty("oracle.driver"));
            bds.setUrl(myProp.getProperty("oracle.url"));
            bds.setUsername(myProp.getProperty("oracle.username"));
            bds.setPassword(myProp.getProperty("oracle.password"));
            bds.setInitialSize(Integer.parseInt(myProp.getProperty("oracle.initSize", "1")));
            bds.setMaxTotal(Integer.parseInt(myProp.getProperty("oracle.maxTotal", "3")));
            bds.setMaxIdle(Integer.parseInt(myProp.getProperty("oracle.maxIdle", "3")));
            bds.setMinIdle(Integer.parseInt(myProp.getProperty("oracle.miniIdle", "1")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取连接
     *
     * @return
     */
    public static Connection getConnection() {
        /*
         * 需要从数据库连接池返回一个连接给调用者
		 */
        Connection conn = null;
        try {
            conn = bds.getConnection();
        } catch (SQLException s) {
            LOG.error("oracle连接失败！！！");
            s.printStackTrace();
        }
        return conn;

    }

    /**
     * 关闭连接
     */
    public static void closeConncetion(Connection conn, Statement state, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
